package com.software.loginregister.api;

import android.util.Log;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import org.json.JSONObject;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class LoggingInterceptor implements Interceptor {
    private static final String TAG = "SearchAPI";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        
        // 记录搜索请求参数
        String url = request.url().toString();
        if (url.contains("/works/search")) {
            Log.d(TAG, "搜索请求URL: " + url);
            Log.d(TAG, "搜索参数: " + 
                "\n关键词: " + request.url().queryParameter("keyword") +
                "\n难度: " + request.url().queryParameter("difficulty") +
                "\n食材: " + request.url().queryParameter("ingredients") +
                "\n用户ID: " + request.url().queryParameter("userId") +
                "\n排序方式: " + request.url().queryParameter("sortBy") +
                "\n页码: " + request.url().queryParameter("page") +
                "\n每页数量: " + request.url().queryParameter("pageSize")
            );
        }

        long startTime = System.currentTimeMillis();
        Response response = chain.proceed(request);
        long endTime = System.currentTimeMillis();

        if (url.contains("/works/search") && response.body() != null) {
            String responseBody = response.body().string();
            Log.d(TAG, "搜索响应: " + 
                "\n状态码: " + response.code() +
                "\n耗时: " + (endTime - startTime) + "ms" +
                "\n响应数据: " + responseBody);

            // 重新构建响应体
            return response.newBuilder()
                    .body(ResponseBody.create(response.body().contentType(), responseBody))
                    .build();
        }

        return response;
    }
}